package com.iengoo.inductionms.filter;

import com.iengoo.inductionms.entity.Token;
import com.iengoo.inductionms.entity.User;
import com.iengoo.inductionms.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-03-17 16:28
 */
@Component
public class AuthenticationFilter implements Filter {
    @Autowired
    private TokenService tokenService;

    private List<String> urls = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        urls.add("/login");
        urls.add("/index_m");
        urls.add("/images/");
        urls.add("/js/");
        urls.add("/style/");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        if (!request.getMethod().toUpperCase().equals("OPTIONS")) {
            // 移动端校验
            String token = request.getHeader("token");
            if (token != null) {
                Token retToken = tokenService.findByToken(token);
                if (retToken == null) {
                    throw new RuntimeException("nopower");
                }
            } else {
                // pc 端校验
                String currentURI = request.getRequestURI();
                boolean flag = true;

                for (String url : urls) {
                    if (currentURI.contains(url)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    HttpSession session = request.getSession();
                    User user = (User) session.getAttribute("USER");

                    if (user == null) {
                        ((HttpServletResponse) servletResponse).sendRedirect("/login.html");
                        return;
                    }
                }
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
